package com.example.chiro;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.CursorLoader;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;

public class Arbre extends SherlockFragmentActivity {

	private ViewPagerAdapter viewPagerAdapter;
	private ViewPager viewPager;

	private DB_FICHEARBRE_adapter db_arbre;
	public static Table_arbre table_arbre;
	public static Table_cavite table_cavite;
	public static Table_espece table_espece;
	public static Table_general table_general;

	public static String photo_arbre_path = "";
	public static ArrayList<Donnees_cavite> liste_cavite;
	public static ArrayList<Donnees_espece> liste_espece;
	public static Context context;

	public void onCreate(Bundle savedInstanceState) {
		Log.i("t: Arbre", "oC : debut");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activite_fiche_arbre);

		context=getApplicationContext();
		
		db_arbre = new DB_FICHEARBRE_adapter(getApplicationContext());
		table_arbre = new Table_arbre(getApplicationContext());
		table_general = new Table_general(getApplicationContext());
		table_cavite = new Table_cavite(getApplicationContext());
		table_espece = new Table_espece(getApplicationContext());
		
		// Nécessaire pour chécker si la base de données existe déjà ou non, et sinon, elle est créé.
		db_arbre.open();
		db_arbre.close();

		// On en profite pour connaitre le numéro de la fiche qui va être créée
		table_general.open();
		Slide_general.numerofiche_value = String.valueOf(table_general.compter_nombre_fiche_totale()+1);
		table_general.close();

		liste_cavite = new ArrayList<Donnees_cavite>();
		liste_espece = new ArrayList<Donnees_espece>();

		Slide_cavite.num_cavite = 1;
		Slide_espece.num_espece = 1;
		Slide_arbre.photo_verouille = false;
		
		setUpView();
		setTab();

		Log.i("t: Arbre", "oC : fin");
	}

	private void setTab() {
		Log.i("t: Arbre", "setTab : debut");
		this.viewPager.setOnPageChangeListener(new OnPageChangeListener() {

			public void onPageScrollStateChanged(int position) {
			}

			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			public void onPageSelected(int position) {
				switch (position) {
				case 0:
					findViewById(R.id.slide_general)
							.setVisibility(View.VISIBLE);
					findViewById(R.id.slide_arbre)
							.setVisibility(View.INVISIBLE);
					findViewById(R.id.slide_cavite).setVisibility(
							View.INVISIBLE);
					findViewById(R.id.slide_espece).setVisibility(
							View.INVISIBLE);
					break;

				case 1:
					findViewById(R.id.slide_general).setVisibility(
							View.INVISIBLE);
					findViewById(R.id.slide_arbre).setVisibility(View.VISIBLE);
					findViewById(R.id.slide_cavite).setVisibility(
							View.INVISIBLE);
					findViewById(R.id.slide_espece).setVisibility(
							View.INVISIBLE);
					break;

				case 2:
					findViewById(R.id.slide_general).setVisibility(
							View.INVISIBLE);
					findViewById(R.id.slide_arbre)
							.setVisibility(View.INVISIBLE);
					findViewById(R.id.slide_cavite).setVisibility(View.VISIBLE);
					findViewById(R.id.slide_espece).setVisibility(
							View.INVISIBLE);
					break;
				case 3:
					findViewById(R.id.slide_general).setVisibility(
							View.INVISIBLE);
					findViewById(R.id.slide_arbre)
							.setVisibility(View.INVISIBLE);
					findViewById(R.id.slide_cavite).setVisibility(
							View.INVISIBLE);
					findViewById(R.id.slide_espece).setVisibility(View.VISIBLE);
					break;
				}

			}

		});
		Log.i("t: Arbre", "setTab : fin");
	}

	private void setUpView() {
		Log.i("t: Arbre", "setUpView : debut");

		this.viewPager = (ViewPager) findViewById(R.id.viewPager);
		this.viewPagerAdapter = new ViewPagerAdapter(getApplicationContext(),
				getSupportFragmentManager());
		this.viewPager.setOffscreenPageLimit(this.viewPagerAdapter.getCount());
		this.viewPager.setAdapter(this.viewPagerAdapter);
		this.viewPager.setCurrentItem(0);

		Log.i("t: Arbre", "setUpView : fin");
	}

	protected void onStop() {
		Log.i("t: Arbre", "onStop : debut");
		super.onStop();
	}

	protected void onStart() {
		Log.i("t: Arbre", "onStart");
		super.onStart();
	}

	protected void onRestart() {
		Log.i("t: Arbre", "onRestart");
		super.onRestart();
	}

	protected void onResume() {
		Log.i("t: Arbre", "onResume");
		super.onResume();
	}

	protected void onPause() {
		Log.i("t: Arbre", "onPause");
		super.onPause();
	}

	protected void onDestroy() {
		Log.i("t: Arbre", "onDestroy");
		super.onDestroy();
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.menu_fiche_arbre, menu);
		return true;

	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_fiche_arbre_action_stocker:
			Toast.makeText(this, "Je stock ! (general / arbre pour l'instant)",
					Toast.LENGTH_SHORT).show();

			table_general.open();
			table_arbre.open();
			table_cavite.open();
			table_espece.open();
			
			table_general.inserer_parSlide(Slide_general.recolte_donnees());
			table_arbre.inserer_parSlide(Slide_arbre.recolte_donnees());
			
			table_cavite.inserer_parSlide(Slide_cavite.recolte_donnees());
			table_espece.inserer_parSlide(Slide_espece.recolte_donnees());
			
			table_cavite.close();
			table_espece.close();
			table_general.close();
			table_arbre.close();
			Slide_general.numerofiche.setText(String.valueOf(Integer.parseInt((String) Slide_general.numerofiche.getText())+1));
			Slide_general.numerofiche_value = String.valueOf(Integer.parseInt(Slide_general.numerofiche_value) + 1);
			Slide_arbre.deverouiller_photo();
			break;
			// Slide_arbre.recolte_donnees();
			// Slide_general.recolte_donnees();

		case R.id.menu_fiche_arbre_action_envoyer:
			/*
			ConnectivityManager connexion = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
			NetworkInfo info = connexion.getActiveNetworkInfo();
			if (info == null || !info.isConnected()){
				Toast.makeText(this, "Internet ne semble pas accessible !", Toast.LENGTH_SHORT).show();
				break;
			}
			*/
			//Pour l'instant, nous n'envoyons que les données générales et arbre
			
			
			
			//Log.i("general", general.getColumnNames()+" "+general.getCount());
			//Log.i("arbre", arbre.getColumnNames()+" "+arbre.getCount());
			
			if (internet_isenable())
				new HTTPSendData().execute();
			else 
				showSettingsAlert();
			//Toast.makeText(this, "Je valide !!", Toast.LENGTH_SHORT).show();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private boolean internet_isenable() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if (netInfo != null && netInfo.isConnectedOrConnecting()) {
			return true;
		}
		return false;
	}

	// Callback de startActivityForResult
	// id: 1111 => retour photo d'arbre
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.i("t: Arbre", "onActivityResult : debut");
		if (resultCode != RESULT_OK)
			return; // si on annule la prise de photo
		if (requestCode ==  1111){  // reçoit une photo arbre
			photo_arbre_path = getRealPathFromURI(data.getData());
			compress(photo_arbre_path, 5);
			Slide_arbre.verouiller_photo();
			
			Log.i("photo path", photo_arbre_path);
		}
		if (requestCode < 200){	//reçoit une photo de cavité
			Toast.makeText(context, "Je reçois la photo cavité de la position"+requestCode%100, Toast.LENGTH_SHORT).show();
			getContentResolver().delete(data.getData(), null, null);
		}
		
		Log.i("t: Arbre", "onActivityResult : fin");
	}
	
	private String getRealPathFromURI(Uri contentUri) {
	    String[] proj = { MediaStore.Images.Media.DATA };
	    CursorLoader loader = new CursorLoader(context, contentUri, proj, null, null, null);
	    Cursor cursor = loader.loadInBackground();
	    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	    cursor.moveToFirst();
	    return cursor.getString(column_index);
	}

	//Fonction qui permet de compresser les photos prises par l'appareil
	private void compress(String path, int facteur){
		Bitmap temp = BitmapFactory.decodeFile(path);
		temp = Bitmap.createScaledBitmap(temp, temp.getWidth()/facteur, temp.getHeight()/facteur, false);
		
		ByteArrayOutputStream bytes = new ByteArrayOutputStream();
		temp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
		File f = new File(path);
		FileOutputStream fo;
		try {
			fo = new FileOutputStream(f);
			fo.write(bytes.toByteArray());
			fo.close();
			temp.recycle();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);

        // Setting Dialog Title
        alertDialog.setTitle("Configuration Internet");

        // Setting Dialog Message
        alertDialog
                .setMessage("Internet semble indisponible. Voulez vous aller aux options de votre appareil?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Options",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent();
                        intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.WirelessSettings"));
                        startActivity(intent);
                    }
                });

        // on pressing cancel button
        alertDialog.setNegativeButton("Annuler",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

        // Showing Alert Message
        alertDialog.show();
    }
	
}
